<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="city">
    <button id="now">查询当前天气</button>
    <button id="future">查询未来天气</button>
    <div id="weather"></div>

    <script>
        /**
         * 天气查询
         * 利用高德地图 API 实现
         ***/
        let city = document.getElementById('city');
        let now = document.getElementById('now');
        let future = document.getElementById('future');
        let weatherInfo = document.getElementById('weather');
        let key= "d2924ac90fbb65d2696bdefa83e52da9";
        let xmlhttp = new XMLHttpRequest();

        now.onclick = function (ev){
            getWeather(ev);
        };
        future.onclick = function (ev){
            getWeather(ev);
        };

        function getWeather(ev){
            let url = "https://restapi.amap.com/v3/weather/weatherInfo?key=";

            if (ev.target.id==="now"){
                xmlhttp.open("GET", url+key+"&city="+city.value, true);
                xmlhttp.send(null);
                xmlhttp.onreadystatechange = function (){
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
                        let weather = JSON.parse(xmlhttp.responseText);
                        if (Number(weather.count) > 0) {
                            weatherInfo.innerText = "当前 " + city.value + " 的天气是：" + weather.lives[0].weather + "，温度是：" + weather.lives[0].temperature + "℃"
                        }
                        else{
                            weatherInfo.innerText = "没有该城市当前天气信息"
                        }
                    }else{
                        weatherInfo.innerText = "请求失败"
                        // 后面可以写重试以及错误处理
                    }
                }
            }else if (ev.target.id==="future"){
                xmlhttp.open("GET", url+key+"&city="+city.value+"&extensions=all", true)
                xmlhttp.send(null);
                xmlhttp.onreadystatechange = function (){
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
                        console.log("WTF")
                        let weather = JSON.parse(xmlhttp.responseText);
                        if (Number(weather.count) > 0) {
                            for (let i=0; i<weather.forecasts[0].casts.length; i++){
                                let div = document.createElement("div");
                                div.innerText = weather.forecasts[0].casts[i].date + " " + weather.forecasts[0].casts[i].dayweather + " " + weather.forecasts[0].casts[i].daytemp + "℃"
                                weatherInfo.appendChild(div)
                            }
                        }else{
                            weatherInfo.innerText = "没有该城市未来 4 天天气信息"
                        }
                    }
                }
            }
            return;
        }
    </script>
</body>
</html>